package com.jay.codec.soft.mp3

import android.util.Log
import com.jay.codec.utils.ByteUtils
import com.jay.codec.utils.IntUtils

/**
 * @author xuzhou4
 * @date 2022/1/7
 */
class FrameHeader(var byteArray: ByteArray) {

    val TAG = "FrameHeader"

    /**
     * 同步信息
     */
    var sync: Int = 0x7FF

    /**
     * 版本
     */
    var version: Int = 0

    /**
     * 层
     */
    var layer: Int = 0

    /**
     * CRC校验
     */
    var crc: Int = 0

    /**
     * 位率
     */
    var bitRate: Int = 0

    /**
     * 采样频率
     */
    var sampleRate: Int = 0

    /**
     * 帧长调节
     */
    var padding: Int = 0

    /**
     * 保留字
     */
    var private: Int = 0

    /**
     * 声道模式
     */
    var mode: Int = 0

    /**
     * 扩充模式
     */
    var extension: Int = 0

    /**
     * 版权
     */
    var copyright: Int = 0

    /**
     * 原版标志
     */
    var original: Int = 0

    /**
     * 强调模式
     */
    var emphasis: Int = 0

    init {
        if (byteArray.size >= 4) {
            val toInt = ByteUtils.toInt(byteArray)

            sync = IntUtils.getInt(toInt, 20, 11)
            version = IntUtils.getInt(toInt, 18, 2)
            layer = IntUtils.getInt(toInt, 16, 2)
            crc = IntUtils.getInt(toInt, 15, 1)
            bitRate = IntUtils.getInt(toInt, 11, 4)
            sampleRate = IntUtils.getInt(toInt, 9, 2)
            padding = IntUtils.getInt(toInt, 8, 1)
            private = IntUtils.getInt(toInt, 7, 1)
            mode = IntUtils.getInt(toInt, 6, 2)
            extension = IntUtils.getInt(toInt, 4, 2)
            copyright = IntUtils.getInt(toInt, 3, 1)
            original = IntUtils.getInt(toInt, 2, 1)
            emphasis = IntUtils.getInt(toInt, 0, 2)
            Log.d(TAG, toString())
        }
    }

    override fun toString(): String {
        return "FrameHeader(byteArray=${byteArray.contentToString()}, sync=$sync, version=$version, layer=$layer, crc=$crc, bitRate=$bitRate, sampleRate=$sampleRate, padding=$padding, private=$private, mode=$mode, extension=$extension, copyright=$copyright, original=$original, emphasis=$emphasis)"
    }
}